package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    private final ReportMapper reportMapper;

    private final WorkspaceService webSpaceService;


    /**
     * 营业额统计
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        if (begin == null || end == null || end.isBefore(begin)){
            throw new RuntimeException("开始时间不能为空，且不能大于结束时间");
        }

        long daysBetween = ChronoUnit.DAYS.between(begin, end);

        if (daysBetween > 32){
            throw new RuntimeException("不能查询超过32天的数据");
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();

        List<LocalDate> dateList = new ArrayList<>();
        // 计算日期
        dateList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        // 构造dateList数据
        String dateStr = String.join(",", dateList.stream().map(LocalDate::toString).toArray(String[]::new));

        turnoverReportVO.setDateList(dateStr);


        // 查询日营业额数据
        List<Double> turnboverList = new ArrayList<>();

        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double turnover = reportMapper.getTurnoverByDate(beginTime,endTime);
            if (turnover == null){
                turnover = 0.0;
            }
            turnboverList.add(turnover);
        });

        // 构造turnoverList数据
        String turnoverStr = String.join(",", turnboverList.stream().map(String::valueOf).toArray(String[]::new));

        turnoverReportVO.setTurnoverList(turnoverStr);

        return turnoverReportVO;
    }

    @Override
    @Transactional
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        if (begin == null || end == null || end.isBefore(begin)){
            throw new RuntimeException("开始时间不能为空，且不能大于结束时间");
        }

        long daysBetween = ChronoUnit.DAYS.between(begin, end);

        if (daysBetween > 32){
            throw new RuntimeException("不能查询超过32天的数据");
        }


        List<LocalDate> dateList = new ArrayList<>();
        List<Long> totalUserList = new ArrayList<>();
        List<Long> newUserList = new ArrayList<>();

        //日期，以逗号分隔，
        dateList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //用户总量
            Map map = new HashMap();
            map.put("endTime",endTime);
            Long totalUserNum = reportMapper.countByMap(map);
            if(totalUserNum == null){
                totalUserNum = 0L;
            }
            totalUserList.add(totalUserNum);
            //新增用户
            map.put("beginTime",beginTime);
            Long newUserNum = reportMapper.countByMap(map);
            if(newUserNum == null){
                newUserNum = 0L;
            }
            newUserList.add(newUserNum);
        });

        String dateString = String.join(",", dateList.stream().map(LocalDate::toString).toArray(String[]::new));
        String totalUserString = String.join(",", totalUserList.stream().map(String::valueOf).toArray(String[]::new));
        String newUserString = String.join(",", newUserList.stream().map(String::valueOf).toArray(String[]::new));


        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(dateString)
                .totalUserList(totalUserString)
                .newUserList(newUserString)
                .build();

        return userReportVO;
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        if (begin == null || end == null || end.isBefore(begin)){
            throw new RuntimeException("开始时间不能为空，且不能大于结束时间");
        }

        long daysBetween = ChronoUnit.DAYS.between(begin, end);

        if (daysBetween > 32){
            throw new RuntimeException("不能查询超过32天的数据");
        }

        // 构造dateList数据
        List<LocalDate> dateList = new ArrayList<>();
        // 每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        // 每天有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();

        dateList.add(begin);

        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);

            // 查询每天订单数
            Integer orderCount = reportMapper.countOrderByMap(map);
            if(orderCount == null) orderCount = 0;
            orderCountList.add(orderCount);


            // 查询每天有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = reportMapper.countOrderByMap(map);
            if(validOrderCount == null) validOrderCount = 0;
            validOrderCountList.add(validOrderCount);

        });

        String dateString = String.join(",", dateList.stream().map(LocalDate::toString).toArray(String[]::new));
        String orderCountString = String.join(",", orderCountList.stream().map(String::valueOf).toArray(String[]::new));
        String validOrderString = String.join(",", validOrderCountList.stream().map(String::valueOf).toArray(String[]::new));

        //订单总数 totalOrderCount;
        Integer total = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数 validOrderCount;
        Integer valid = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率 orderCompletionRate;
        Double completion = 0.0;
        if(total != 0){
            completion = valid.doubleValue() / total;
        }


        return OrderReportVO.builder()
                .dateList(dateString)
                .orderCountList(orderCountString)
                .validOrderCountList(validOrderString)
                .totalOrderCount(total)
                .validOrderCount(valid)
                .orderCompletionRate(completion)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        if (begin == null || end == null || end.isBefore(begin)){
            throw new RuntimeException("开始时间不能为空，且不能大于结束时间");
        }

        // 菜名
        List<String> nameList = new ArrayList<>();

        // 菜品销量
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = reportMapper.getTop10(beginTime, endTime);

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();

        if(list != null && !list.isEmpty()){
            //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
            List<String> name = new ArrayList<>();
            //销量列表，以逗号分隔，例如：260,215,200
            List<Integer> number = new ArrayList<>();

            list.forEach(good -> {
                name.add(good.getName());
                number.add(good.getNumber());
            });

            String nameString = String.join(",", name.stream().map(x -> x).toArray(String[]::new));
            String numberString = String.join(",", number.stream().map(String::valueOf).toArray(String[]::new));

            salesTop10ReportVO.setNameList(nameString);
            salesTop10ReportVO.setNumberList(numberString);
        }

        return salesTop10ReportVO;
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询数据库，获取营业数据 -- 最近30天
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(-1);

        BusinessDataVO businessData =
                webSpaceService.getBusinessData(
                        LocalDateTime.of(dateBegin, LocalTime.MIN),
                        LocalDateTime.of(dateEnd, LocalTime.MAX));
        // 2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass()
                .getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");

        if (in == null || businessData == null){
            throw new RuntimeException("文件不存在");
        }

        try {
            // 2.1 基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获取标签页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 填充数据 -- 时间
            sheet1.getRow(1).getCell(1).setCellValue("时间："+dateBegin + "至" + dateEnd);
            // 营业金额 3-2  4  6
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            // 订单完成率 3-4
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            // 新增用户数 3-6
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            // 有效订单 4-2
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            // 平均客单价 4-4
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            for(int i=0;i<30;i++){
                BusinessDataVO data =
                        webSpaceService.getBusinessData(
                                LocalDateTime.of(dateBegin.plusDays(i), LocalTime.MIN),
                                LocalDateTime.of(dateBegin.plusDays(i), LocalTime.MAX));
                // 日期
                sheet1.getRow(7 + i).getCell(1).setCellValue(dateBegin.plusDays(i).toString());
                // 营业额
                sheet1.getRow(7 + i).getCell(2).setCellValue(data.getTurnover());
                // 有效订单
                sheet1.getRow(7 + i).getCell(3).setCellValue(data.getValidOrderCount());
                // 订单完成率
                sheet1.getRow(7 + i).getCell(4).setCellValue(data.getOrderCompletionRate());
                // 平均客单价
                sheet1.getRow(7 + i).getCell(5).setCellValue(data.getUnitPrice());
                // 新增用户数
                sheet1.getRow(7 + i).getCell(6).setCellValue(data.getNewUsers());

            }

            // 3.通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private static LocalDate getDate(LocalDate dateBegin, int i) {
        return dateBegin.plusDays(i);
    }
}
